<?php

namespace Liuhelong\LaravelAdmin\Wechat\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Storage;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Support\Facades\Cache;

class WechatOffiaccountMenu extends Model
{
    use DefaultDatetimeFormat,ModelTree;
	
	private $wechat;
	protected $appends = ['link'];
	
	public function __construct(array $attributes = []){
		parent::__construct($attributes);

        $this->setTitleColumn('name');
		$this->wechat = app('liuhelong_wechat_service');
	}
	
	
	public function getLinkAttribute()
    {
        return $this->type=='view'?$this->url:'';
    }
	
	public function get($columns = ['*'])
    {
		$list = Cache::rememberForever('menus', function() {
		    try{
    			$data = $this->wechat->handle('menu','list');
    			$menus = $data['menu']['button'];
    			
    			$id = 0;
    			$list = [];
    			foreach($menus as $k=>$menu){
    				$id++;
    				
    				$menu['id'] = $id;
    				$menu['parent_id'] = 0;
    				$menu['order'] = $id;
    				unset($menu['sub_button']);
    				$list[$id] = $menu;
    					   
    				if(!empty($menus[$k]['sub_button'])){
    					foreach($menus[$k]['sub_button'] as $l=>$son){
    						$id++;
    						
    						$son['id'] = $id;
    						$son['parent_id'] = $menu['id'];
    						$son['order'] = $id;
    						unset($son['sub_button']);
    						
    						$list[$id] = $son;
    					}
    				}
    			}
    			return $list;
		    }catch(\Exception $e){
		        return [];
		    }
		});
		//dump($list);
		$list = static::hydrate($list)->sortBy('order');
        return $list;
		
    }
	public function orderByRaw()
    {
		return $this;
    }

    public static function with($relations)
    {
        return new static;
    }
	
	public function findOrFail($id)
	{		
		return static::newFromBuilder(cache('menus')[$id]);
	}
	public function save(array $options = [])
	{
		$attributes = $this->getAttributes();
		$menus = cache('menus');
		
		$menu = [
			'name'=>$attributes['name'],
			'parent_id'=>$attributes['parent_id']?:0,
			'type'=>$attributes['type']
		];
		
		switch($attributes['type']){
			case('view'):
				$menu['url']=$attributes['link'];
				break;
			case('click'):
				$menu['key']=$attributes['key'];
				break;
			case('miniprogram'):
				$menu['appid']=$attributes['appid'];
				$menu['pagepath']=$attributes['pagepath'];
				$menu['url']=$attributes['url'];
				break;
			case(''):
				break;
			default:
				$menu['key']=$attributes['key'];
				break;
		}
		//更新操作
		if(!empty($attributes['id'])){
			$menu['id'] = $attributes['id'];
			$menu['order'] = $attributes['order'];
			
			$menus[$attributes['id']] = $menu;			
		}else{			
			$menu['id'] = (end($menus)['id']??0)+1;
			$menu['order'] = 99;
			
			$menus[$menu['id']] = $menu;					
		}
		
		cache(['menus'=>$menus]);
		
	}
	
}
